package com.myb.common.util;

import cn.hutool.json.JSONUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author meiyubin
 * @Date 2023/12/6
 * @DESC
 */
@Component
public class BeanUtil {
    /**
     * 将任意类型转换成字符串
     *
     * @param value
     * @param <T>
     * @return
     */
    public static <T> String beanToString(T value) {
        Class<?> clazz = value.getClass();
        if (clazz == int.class || clazz == Integer.class) {
            return value + "";
        } else if (clazz == String.class) {
            return (String) value;
        } else if (clazz == long.class || clazz == Long.class) {
            return value + "";
        } else {
            return JSONUtil.toJsonStr(value);
        }
    }

    /**
     * 把一个字符串转换成bean对象
     *
     * @param str
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T stringToBean(String str, Class<T> clazz) {
        if (str == null || str.length() <= 0 || clazz == null) {
            return null;
        }
        if (clazz == int.class || clazz == Integer.class) {
            return (T) Integer.valueOf(str);
        } else if (clazz == String.class) {
            return (T) str;
        } else if (clazz == long.class || clazz == Long.class) {
            return (T) Long.valueOf(str);
        } else {
            return JSONUtil.toBean(JSONUtil.parse(str).toString(), clazz);
        }
    }

    /**
     * List<T> 转换成 List<V> 直接copy
     *
     * @param sourceList
     * @param targetClass
     * @return List<V>
     * @author meiyubin
     */
    public static <T, V> List<V> convertToVOList(List<T> sourceList, Class<V> targetClass) {
        List<V> targetList = new ArrayList<>();
        for (T source : sourceList) {
            try {
                V target = targetClass.newInstance();
                BeanUtils.copyProperties(source, target);
                targetList.add(target);
            } catch (InstantiationException | IllegalAccessException e) {
                // 处理异常
            }
        }
        return targetList;
    }

    /**
     * 实体直接copy
     *
     * @param source
     * @param targetClass
     * @return V
     * @author meiyubin
     */
    public static <T, V> V convertToVO(T source, Class<V> targetClass) {
        try {
            V target = targetClass.newInstance();
            BeanUtils.copyProperties(source, target);
            return target;
        } catch (InstantiationException | IllegalAccessException e) {
            // 处理异常
        }
        return null;
    }
}
